<?php


namespace payment\leisenpay;


class leisenpay
{
    protected $appId;
    protected $apiKey;
    protected $payKey;


    //私钥值
    protected $rsaPrivateKey;
    public function __construct($config)
    {
        $this->appId = $config['app_id'];
        $this->apiKey = $config['app_key'];
        $this->payKey=$config['pay_key'];
    }

    /**
     * 转帐
     * @param float $totalFee 转账金额，单位：元。
     * @param string $outTradeNo 商户转账唯一订单号
     * @param string $remark 转帐备注
     * @return array
     */
//    public function transfer($totalFee, $outTradeNo, $account,$realName,$remark='',$payee_type=2)
    public function transfer($params)
    {
        $commonConfigs = array(
            //公共参数
            'api_id' => $this->appId,
            'pay_pass' => $this->payKey,
            'out_biz_no'=>$params['out_trade_no'],
            'payee_type'=>$params['payee_type'],
            'payee_account'=>$params['account'],
            'payee_name'=>$params['real_name'],  //收款方真实姓名
            'money'=>$params['amount'], //转账金额，单位：元。
            'remark'=>$params['remark'],  //转账备注（选填）
            'timestamp'=>time(),
        );

        $commonConfigs["sign"] = $this->generateSign($commonConfigs, $this->apiKey);

        $result = $this->curlPost('https://pay.leisen.tech/api/transfer/submit.html',$commonConfigs);
        $jsonArray = json_decode($result,true);

        if ($jsonArray['code'] != 1) {
            if($jsonArray['msg']=='账号和姓名不匹配，请确认姓名是否正确'){
                $jsonArray['status']=-1;
            }else{
                $jsonArray['status']=0;
            }
            $jsonArray['msg']=$jsonArray['msg'];
            return $jsonArray;
        }


        $jsonArray['status']=1;
        $jsonArray['back_transaction_no']=$jsonArray['order_id'];
        return $jsonArray;

    }



    public function generateSign($param, $key) {
        $signPars = "";
        ksort($param);
        foreach ($param as $k => $v) {
            if ("sign" != $k && "" != $v) {
                $signPars .= $k . "=" . $v . "&";
            }
        }
        $signPars = trim($signPars, '&');
        $signPars .= $key;
        $sign = md5($signPars);
        return $sign;
    }




    public function curlPost($url = '', $postData = '', $options = array())
    {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
}